<template>
    <div class="box">
        <el-form :inline="true" :model="forms" class="demo-form-inline">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="渠道名称">
                        <el-input v-model="forms.channelName" placeholder="请输入渠道名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="渠道状态">
                        <el-select v-model="forms.status" placeholder="渠道状态" clearable>
                            <el-option label="正常" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="渠道类型">
                        <el-select v-model="forms.type" placeholder="渠道状态" clearable>
                            <el-option label="线上渠道" :value="1" />
                            <el-option label="线下渠道" :value="2" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="创建时间">
                        <el-date-picker v-model="forms.createTime" type="daterange" range-separator="-"
                            start-placeholder="开始日期" end-placeholder="结束日期" :size="size" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
                        <el-button :icon="Refresh" @click="resetForm">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="10">
                    <template #default="scope">
                        <el-button type="primary" :icon="Plus" plain @click="show">新增</el-button>
                        <el-button type="success" :icon="Edit" plain :disabled="delId.length != 1"
                            @click="edit(null)">修改</el-button>
                        <el-button type="info" :icon="Delete" plain :disabled="delId.length != 1"
                            @click="del(null)">删除</el-button>
                        <el-button type="warning" :icon="Upload"  @click="handleImport" plain>导入</el-button>
                        <el-button type="danger" :icon="Download"  @click="exportXLsx" plain>导出</el-button>
                    </template>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="table">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="channelId" label="渠道编号" width="150" />
            <el-table-column prop="channelName" label="渠道名称" width="150" show-overflow-tooltip />
            <el-table-column prop="type" label="渠道类型" width="150">
                <template v-slot="scope">
                    <el-tag type="success" v-if="scope.row.type == 2">线下渠道</el-tag>
                    <el-tag type="primary" v-if="scope.row.type == 1">线上渠道</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="渠道状态" width="150">
                <template v-slot="scope">
                    <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
                    <el-tag type="primary" v-if="scope.row.status == 0">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="updateBy" label="创建人" width="150" />
            <el-table-column prop="createTime" label="创建时间" width="200" />
            <el-table-column prop="remark" label="备注信息" width="150" show-overflow-tooltip />
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
                        <el-icon color="#409efc" class="no-inherit" @click="edit(scope.row.channelId)">
                            <Edit />
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                        <el-icon color="#409efc" class="no-inherit" @click="del(scope.row.channelId)">
                            <Delete />
                        </el-icon>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <div class="foot">
            <page :pageParams="pageParams" :total="total" @size-change="pageChange"
                @currentChange="handleCurrentChange">
            </page>
        </div>
    </div>
    <!-- 新增 -->
    <el-dialog v-model="dialogVisible" :title="title" width="35%">
        <div>
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
                <el-form-item label="渠道名称" prop="channelName">
                    <el-input v-model="ruleForm.channelName" />
                </el-form-item>
                <el-form-item label="渠道状态" prop="status">
                    <el-radio-group v-model="ruleForm.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="渠道类型" prop="type">
                    <el-radio-group v-model="ruleForm.type">
                        <el-radio :label="1">线上渠道</el-radio>
                        <el-radio :label="2">线下渠道</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="ruleForm.remark" type="textarea" />
                </el-form-item>
                <div class="foot">
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetDialogForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </div>
            </el-form>

        </div>
    </el-dialog>

       <!-- 用户导入对话框 -->
        <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
            <el-upload
                ref="uploadRef"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip">
                            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                        </div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link
                            type="primary"
                            :underline="false"
                            style="font-size: 12px; vertical-align: baseline"
                            @click="importTemplate"
                            >下载模板</el-link
                        >
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
</template>
<script lang="ts" setup>
import { list, add, detail, updata, userdel,channelOut } from "../../../api/channel";
import page from "@/components/page.vue";
import { Search, Refresh, Plus, Edit, Delete, Download, Upload } from '@element-plus/icons-vue';
import { reactive, ref, onMounted, nextTick,getCurrentInstance, ComponentInternalInstance,  } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { getToken } from '@/utils/auth';
import { ElMessage, ElMessageBox } from 'element-plus'; // 导入 ElMessage
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 定义 getToken 函数
const getToken = () => {
    return localStorage.getItem('token') || '';
};

/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/tienchin/channel/importData',
});

/** 导入按钮操作 */
function handleImport() {
    upload.title = '用户导入';
    upload.open = true;
}
/** 下载模板操作 */
function importTemplate() {
    proxy!.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`);
}
/**文件上传中处理 */
const handleFileUploadProgress = (event?: any, file?: any, fileList?: any) => {
    upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any, fileList: any) => {
    upload.open = false;
    upload.isUploading = false;
    (proxy?.$refs['uploadRef'] as any).handleRemove(file);
    (proxy as any).$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
    );
    getList();
};
/** 提交上传文件 */
function submitFileForm() {
    (proxy?.$refs['uploadRef'] as any).submit();
}

const delId = ref<any[]>([]); // 定义 delId
const handleSelectionChange = (val: any) => {
    delId.value = [];
    for (const item of val) {
        delId.value.push(item.channelId)
    }
}
let title = ref('');
interface RuleForm {
    channelName: string;
    status: number | undefined;
    type: number | undefined;
    remark: string;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    channelName: '',
    status: undefined,
    type: undefined,
    remark: '',
    // createBy: '',
    // createTime: '',
    // delFlag: '',
    // updateBy: '',
    // updateTime: '',
});
const rules = reactive<FormRules<RuleForm>>({
    channelName: [
        { required: true, message: '请输入渠道名称', trigger: 'blur' },
    ],
    remark: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ],
});

// 定义 channelId
const channelId = ref('');

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === "添加渠道") {
                // 新增接口
                add(ruleForm).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    });
                    dialogVisible.value = false;
                }).catch(err => {
                    if (err.code === 188) {
                        ElMessage.error('用户名已存在');
                    }
                });
            } else {
                // 修改
                updata({
                    channelId: delId.value,
                    ...ruleForm
                }).then(res => {
                    ElMessage.success("修改成功");
                    dialogVisible.value = false;
                });
            }
        } else {
            console.log('error submit!', fields);
        }
    });
};

// 导出
const exportXLsx = (() => {
    channelOut(forms).then(res => {
        console.log(res, "导出成功");
        // 创建一个blob对象，存储excel文件的数据
        let blob = new Blob([res])
        // 创建一个a标签
        const link = document.createElement("a")
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute("download", `导出课程${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err, "导出失败");
        })
})
const resetDialogForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    dialogVisible.value = false;
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));
let total = ref(0);
let id = ref(0);
// 定义表单初始值
const initialForms = {
    channelName: '',
    status: '',
    type: '',
    createTime: '',
};
const forms = reactive({ ...initialForms });
const tableData = ref<any[]>([]);

const onSubmit = () => {
    console.log('submit!');
};
const pageParams = reactive({
    pageNum: 1,
    pageSize: 10,
});
const dialogVisible = ref(false);

onMounted(() => {
    getList();
});

// 打开弹框
function show() {
    dialogVisible.value = true;
    title.value = "添加渠道";
    // 重置表单
    nextTick(() => {
        ruleFormRef.value?.resetFields();
    });
}

// 编辑
function edit(row) {
    if (row) {
        delId.value = row;
    }
    console.log(delId.value)
    dialogVisible.value = true
    title.value = "修改渠道"
    // 获取详情
    detail(delId.value).then(res => {
        console.log(res);
        ruleForm.channelName = res.data.channelName
        // ruleForm.createBy = res.data.createBy
        // ruleForm.createTime = res.data.createTime
        // ruleForm.delFlag = res.data.delFlag
        // ruleForm.updateBy = res.data.updateBy
        // ruleForm.updateTime = res.data.updateTime
        ruleForm.status = res.data.status
        ruleForm.type = res.data.type
        ruleForm.remark = res.data.remark
        delId.value = res.data.channelId
    })

}

// 删除
function del(channelId: number) {
    if (channelId) {
        delId.value = channelId;
    }
    ElMessageBox.confirm(`此操作将永久删除编号为${delId.value}的数据, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        userdel(delId.value).then(res => {
            ElMessage.success('删除成功');
            getList();
        }).catch(err => {
            ElMessage.error(err.msg);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 获取列表
function getList() {
    // 传递 pageParams 到接口
    list({ ...forms, ...pageParams }).then(res => {
        console.log(res);
        tableData.value = res.rows;
        total.value = res.total;
    });
}

// 接收子传父数据 条数改变时
const pageChange = (val: number) => {
    pageParams.pageNum = 1;
    pageParams.pageSize = val;
    getList();
};

function search() {
    pageParams.pageNum = 1;
    getList();
}

const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    pageParams.pageNum = val;
    getList();
};

// 重置表单函数
const resetForm = () => {
    // 重置表单数据
    Object.assign(forms, initialForms);
    // 重置分页参数
    pageParams.pageNum = 1;
    pageParams.pageSize = 10;
    // 重新获取列表
    getList();
};
</script>

<style scoped lang="scss">
.box {
    padding: 20px;
}

.table {
    margin-left: 10px;
}

.foot {
    display: flex;
    justify-content: right;
}

::deep(.demo-form-inline .el-input__wrapper) {
    width: 320px;
}

::deep(.demo-form-inline .el-select .el-input__wrapper) {
    width: 220px;
}
</style>